import { extend } from 'umi-request';
import { notification } from 'antd';
import md5 from 'md5';

const { PURPLE_BIRD_ENV } = process.env;

const errorHandler = (error: { response: Response }): Response => {
  const { response } = error;
  if (!response) {
    notification.error({
      key: 'updatable',
      message: '网络异常操作失败，请稍后重试',
    });
  }
  return response;
};

/**
 * 配置request请求时的默认参数
 */
const target: any = {
  dev: 'http://47.105.45.115:8080',
  test: 'http://47.105.45.115:8080',
  prod: 'http://47.105.45.115:8080',
};
const prefix = target[PURPLE_BIRD_ENV || 'dev'];
const request = extend({
  prefix,
  errorHandler,
});

// request拦截器, 改变url 或 options.
request.interceptors.request.use(
  (url: string, options: any) => {
    const date = new Date();
    const token = md5(
      `${date.getFullYear()}-${date.getMonth() + 1}-${
        date.getDate() < 10 ? `0${date.getDate()}` : date.getDate()
      } ${date.getHours()}:00:00`,
    );
    if (options.method === 'get') options.params = { ...options.params, token };
    if (options.method === 'post') options.data = { ...options.data, token };
    const headers = {
      'Content-Type': 'application/json',
    };
    return {
      url,
      options: { ...options, headers },
    };
  },
  { global: true },
);

// response拦截器, 处理response
request.interceptors.response.use(async (response: any) => {
  return response;
});

export default request;
